/*
 * Copyright (c)  2015~2020, xforceplus
 * All rights reserved.
 * Project:datacare-orm
 * Id: SQLReadyExecuteMapperInvoke.java   2020-09-30 09-15-47
 * Author: Evan
 */
package cn.datacare.orm.mapper.inovke;

import cn.datacare.orm.manager.impl.SQLManager;
import cn.datacare.orm.mapper.MapperInvoke;
import cn.datacare.orm.mapper.MethodDesc;
import cn.datacare.orm.mapper.parameter.PageQueryParameter;
import cn.datacare.orm.query.PageQuery;
import cn.datacare.orm.source.SQLReady;

import java.lang.reflect.Method;
import java.util.List;

/**
 * <p>
 * Title:
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Copyright: 2015~2020
 * </p>
 * <p>
 * Company/Department: xforceplus
 * </p>
 *
 * @author Evan
 * <b>Creation Time:</b> 2020-09-30 09-15-47
 * @since V1.0
 */
public class SqlReadyExecuteMapperInvoke implements MapperInvoke {

    @Override
    public Object call(SQLManager sm, Class entityClass, String sqlId, Method m, Object[] args) {
        MethodDesc desc = MethodDesc.getMethodDescBySqlId(sm, entityClass, m, sqlId);
        int type = desc.type;
        if (type == MethodDesc.SM_SELECT_SINGLE || type == MethodDesc.SM_SELECT_LIST) {
            Class returnType = desc.resultType;
            List list = sm.execute(new SQLReady(sqlId, args), returnType);
            if (type == MethodDesc.SM_SELECT_SINGLE) {
                return list.size() == 0 ? null : list.get(0);
            } else {
                return list;
            }
        }else if (type == MethodDesc.SM_SQL_READY_PAGE_QUERY) {
            // 分页对象
            PageQueryParameter parameter = (PageQueryParameter)desc.parameter;
            PageQuery pageQuery = (PageQuery)parameter.get(args);
            Object[] jdbcArgs = parameter.getJdbcArgs(args);
            sm.execute(new SQLReady(sqlId,jdbcArgs), entityClass, pageQuery);
            return pageQuery;
        }else{
            return sm.executeUpdate(new SQLReady(sqlId, args));
        }



    }

}
